package com.zou.jokes.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.zou.jokes.Constant;
import com.zou.jokes.R;
import com.zou.jokes.adapter.JokesAdapter;
import com.zou.jokes.beans.JokesBean;
import com.zou.jokes.utils.JsonUtils;
import com.zou.jokes.utils.RxBus;
import com.zou.jokes.utils.SharedPreferencesUtils;
import com.zou.jokes.utils.ToastUtil;
import com.zou.jokes.utils.UserEvent;
import com.zou.jokes.utils.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;

/**
 * Created by zou on 2016/6/2.
 */
public class JokeFragment extends Fragment {

    List<JokesBean.ResultBean.DataBean> datas;
    long                                time;
    String url = "http://japi.juhe.cn/joke/content/list.from";
    private JokesAdapter adapter;
    private String key  = "45396a79d2f4ff6514d5636eebedaf54";
    private int    page = 1;
    private View               lodingView;
    private int                count;
    private Subscription       rxSubscribe;
    private SwipeRefreshLayout swipeRefreshLayout;

    public JokeFragment() {
        this.time = System.currentTimeMillis();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        count = 1;
        View view = inflater.inflate(R.layout.fragment_jokes, container, false);

        String tempJson = (String) SharedPreferencesUtils.getParam(getContext(), Constant.TEMPJOKEJSON, "");


        datas = new ArrayList<>();
        if (!TextUtils.isEmpty(tempJson)) {
            try {
                datas.addAll(((JokesBean) JsonUtils.fromJson(tempJson, JokesBean.class)).getResult().getData());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        adapter = new JokesAdapter(datas, getContext());

        lodingView = view.findViewById(R.id.loding_view);
        lodingView.setVisibility(View.VISIBLE);


        RecyclerView rcv = (RecyclerView) view.findViewById(R.id.rcv);
        rcv.setItemAnimator(new DefaultItemAnimator());
        rcv.setLayoutManager(new LinearLayoutManager(getContext()));
        rcv.setAdapter(adapter);

//        下拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl);
        swipeRefreshLayout.setOnRefreshListener(this::refresh);


        return view;
    }

    //    刷新数据
    private void refresh() {
//        重置数据
        count = 1;
        time = System.currentTimeMillis();
        loadMore();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

//        初次请求
        StringRequest stringRequest = new StringRequest(Request.Method.GET
                , url + new GetParams("desc", count + "", "20", time + "", key).toString()
                , response -> {
            count++;
            SharedPreferencesUtils.setParam(getContext(), Constant.TEMPJOKEJSON, response);
            Log.e("wocao", "onAttach: ");
            Log.e("wocao", "onAttach: " + url + new GetParams("desc", page + "", "20", time + "", key).toString());
            Log.e("wocao", "onAttach: " + response);
            JokesBean res = (JokesBean) JsonUtils.fromJson(response, JokesBean.class);
            datas.clear();
            datas.addAll(res.getResult().getData());
            //            datas.addAll(((JokesBean) JsonUtils.fromJson(response, JokesBean.class)).getResult().getData());
            adapter.notifyDataSetChanged();
//            RxBus.getDefault().post(new UserEvent(Constant.HIDESHOWLOADING, ""));
            lodingView.setVisibility(View.GONE);
        }
                , error -> {

        });

        VolleySingleton.getVolleySingleton(context).addToRequestQueue(stringRequest);
//        通知MainActivity显示Loading
//        RxBus.getDefault().post(new UserEvent(Constant.SHOWLOADING, ""));


        rxSubscribe = RxBus.getDefault().toObserverable(UserEvent.class).subscribe(userEvent -> {
            if (userEvent.getId() == Constant.JOKELOADMORE) {
                loadMore();
                Log.e("wocao", "onAttach: 加载更多");
            } else if (userEvent.getId() == Constant.UPDATEJOKE) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void loadMore() {
        Log.e("wocao", "loadMore: " + url + new GetParams("desc", count + "", "20", time + "", key).toString());
        StringRequest stringRequest = new StringRequest(Request.Method.GET
                , url + new GetParams("desc", count + "", "20", time + "", key).toString()
                , response -> {
            count++;
            adapter.setLoadingMore(false);
            try {
                if (swipeRefreshLayout.isRefreshing()) {
                    datas.clear();
                    swipeRefreshLayout.setRefreshing(false);
                }
                datas.addAll(((JokesBean) JsonUtils.fromJson(response, JokesBean.class)).getResult().getData());
                adapter.notifyDataSetChanged();

            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast(getContext(), e.toString());
            }
        }
                , error -> {
        });
        VolleySingleton.getVolleySingleton(getContext()).addToRequestQueue(stringRequest);
    }


    @Override
    public void onDetach() {
        super.onDetach();
        if (!rxSubscribe.isUnsubscribed()) {
            rxSubscribe.unsubscribe();
        }
    }

    class GetParams {
        String sort, page, pagesize, time, key;

        public GetParams(String sort, String page, String pagesize, String time, String key) {
            this.sort = sort;
            this.page = page;
            this.pagesize = pagesize;
            this.time = time.substring(0, 10);
            this.key = key;
        }

        public void setPage(String page) {
            this.page = page;
        }

        @Override
        public String toString() {
            return "?sort=" + sort +
                    "&page=" + page +
                    "&pagesize=" + pagesize +
                    "&time=" + time +
                    "&key=" + key;
        }
    }


}
